package com.huiyeji.dynamic.core;

import com.huiyeji.sort.MatchRule;

import java.util.Arrays;
import java.util.List;

public class MethodRequestMatchRule implements MatchRule<MethodRequest,MethodRequest> {

    private static final List<String> INT = Arrays.asList("java.lang.Integer", "int");
    private static final List<String> BOOLEAN = Arrays.asList("java.lang.Boolean", "boolean");
    private static final List<String> DOUBLE = Arrays.asList("java.lang.Double", "double");
    private static final List<String> LONG = Arrays.asList("java.lang.Long", "long");
    private static final List<String> FLOAT = Arrays.asList("java.lang.Float", "float");
    private static final List<String> SHORT = Arrays.asList("java.lang.Short", "short");
    private static final List<String> BYTE = Arrays.asList("java.lang.Byte", "byte");
    private static final List<String> CHAR = Arrays.asList("java.lang.Character", "char");



    @Override
    public boolean match(MethodRequest methodRequestSource, MethodRequest methodRequestRule) {
        Class<?>[] bindTypes = methodRequestRule.getParameterTypes();
        Class<?>[] originTypes = methodRequestSource.getParameterTypes();

        if (bindTypes.length != originTypes.length){
            return false;
        }

        for (int i = 0; i < bindTypes.length; i++) {
            if (originTypes[i] == null){
                continue;
            }
            if (!bindTypes[i].isAssignableFrom(originTypes[i])){
                if (!isSameBaseType(bindTypes[i].getName(), originTypes[i].getName())){
                    return false;
                }
            }
        }

        return true;
    }

    private boolean isSameBaseType(String name1, String name2){
        return      INT.contains(name1) && INT.contains(name2)
                || BOOLEAN.contains(name1) && BOOLEAN.contains(name2)
                || DOUBLE.contains(name1) && DOUBLE.contains(name2)
                || LONG.contains(name1) && LONG.contains(name2)
                || FLOAT.contains(name1) && FLOAT.contains(name2)
                || SHORT.contains(name1) && SHORT.contains(name2)
                || BYTE.contains(name1) && BYTE.contains(name2)
                || CHAR.contains(name1) && CHAR.contains(name2);
    }
}
